import 'package:flutter/material.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/module/login/page/login_page.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_svg/svg.dart';
import 'package:logger/logger.dart';
import '../../../api/api.dart';
import '../../../app.dart';
import '../../../generated/r.dart';
import '../../../utils/alib.dart';
import '../../../utils/log.dart';
import '../../../main/widgets/ui_constant.dart';
import '../ext/u_button.dart';
import '../ext/u_text.dart';
import 'layout.dart';
import '../../../utils/tip.dart';

class StateLayoutController {
  StateLayoutState? _stateLayoutState;
  _attatch(StateLayoutState state) {
    _stateLayoutState = state;
  }

  _dettach() {
    _stateLayoutState = null;
  }

  reload() {
    _stateLayoutState?.loadData();
  }
}

class StateLayout extends StatefulWidget {
  Widget Function(dynamic) childBuilder;
  String url;
  String urlMethod;
  dynamic urlData;
  String Function()? urlBuilder;
  String preUrl;
  DataCallback? preDataCallback;
  DataCallback? dataCallback;
  StateLayoutController? controller;
  ErrorCallback? errorCallback;
  StateLayout({
    Key? key,
    required this.url,
    this.urlBuilder,
    this.urlMethod = "GET",
    this.urlData,
    this.preUrl = "",
    required this.childBuilder,
    this.preDataCallback,
    this.dataCallback,
    this.controller,
    this.errorCallback,
  }) : super(key: key);

  @override
  State createState() => StateLayoutState();
}

class StateLayoutState extends State<StateLayout> {
  LayoutState layoutState = LayoutState.Loading;
  dynamic _data;
  bool _hasOkLoad = false;
  var _exceptionMsg = "";
  var _hasException = false;

  @override
  void initState() {
    super.initState();
    widget.controller?._attatch(this);
    loadData();
  }

  @override
  void dispose() {
    super.dispose();
    widget.controller?._dettach();
  }

  @override
  Widget build(BuildContext context) {
    Widget content;
    if (layoutState == LayoutState.Loading) {
      content = Center(
        child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
          SizedBox(
              width: 20.rpx,
              height: 20.rpx,
              child: CircularProgressIndicator(
                strokeWidth: 2.rpx,
                color: UIColor.color_t3,
              )),
          5.hspace,
          UText.getSubText("加载中..."),
        ]),
      );
    } else if (layoutState == LayoutState.Error) {
      content = _getErrorChild();
    } else if (layoutState == LayoutState.NoNet) {
      content = _getNoNetChild();
    } else {
      try {
        content = widget.childBuilder(_data);
      } catch (e, s) {
        var pp = PrettyPrinter();
        _exceptionMsg = pp.formatStackTrace(s, 3) ?? "";
        Log.i("err: ", [e, s]);
        _hasException = true;
        content = _getErrorChild();
      }
    }
    return content;
  }

  Widget _getNoNetChild() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SvgPicture.asset(R.image_not_network, width: 200.rpx, height: 200.rpx),
          24.hspace,
          Row(
              mainAxisAlignment:MainAxisAlignment.center,
              children: [
                UText.get("暂无网络，请", UIColor.color_t3, 16.rpx),
                GestureDetector(
                  onTap: () {
                    loadData();
                  },
                  child: Text(
                    '重新加载',
                    style: TextStyle(
                      fontSize: 16.rpx,
                      color: UIColor.color_primary,
                      decoration: TextDecoration.underline,
                      decorationColor: UIColor.color_primary,
                    ),
                  ),
                )
              ]
          )
        ],
      ),
    );
  }

  Widget _getErrorChild() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          10.hspace,
          UText.getSubText("加载失败"),
          10.hspace,
          UButton.getRoundRectButton("重试",
              backgroundColor: UIColor.color_primary,
              fontSize: 13.rpx,
              radius: 2.rpx,
              width: 72.rpx,
              height: 34.rpx, onPressed: () {
            loadData();
          }),
          10.hspace,
          App.isDebugMode && _hasException ? UText.get(_exceptionMsg, Colors.red, 13.rpx).padding(EdgeInsets.symmetric(horizontal: 20.rpx)) : 0.wspace,
        ],
      ),
    );
  }

  loadData() async {
    if (_data == null) {
      setState(() {
        _hasException = false;
        layoutState = LayoutState.Loading;
      });
    }
    Alib.hasNetwork().then((value) {
      if (value) {
        if (widget.preUrl.isNotEmpty) {
          Api.get(widget.preUrl, (data, response) {
            if (widget.preDataCallback != null) {
              widget.preDataCallback!(data);
            }
            if (data != null) {
              _realLoadData();
            } else {
              _showError();
            }
          });
        } else {
          _realLoadData();
        }
      } else {
        if (widget.errorCallback != null) {
          widget.errorCallback!(_data, ServerResponse());
        }
        setState(() {
          if (_data == null) {
            layoutState = LayoutState.NoNet;
          }
        });
      }
    });
  }

  _realLoadData() {
    if (widget.urlBuilder != null) {
      widget.url = widget.urlBuilder!();
    }
    Api.request(widget.url, widget.urlMethod, widget.urlData, (data, response) {
      if (data != null) {
        _data = data;
        if (widget.dataCallback != null) {
          widget.dataCallback!(data);
        }
        setState(() {
          _hasOkLoad = true;
          layoutState = LayoutState.Content;
        });
      } else {
        if (!_hasOkLoad) {
          if (response.msg.isNotEmpty) {
            // ScaffoldMessenger.of(context)
            //     .showSnackBar(SnackBar(content: UText.get(response.msg, Colors.white, 15.rpx)));
            Tip.show(response.msg);
            if(response.code == -100002){
              Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) {
                return LoginPage();
              }), (route) => false);
            }
          }
          _showError();
        }
        if (widget.errorCallback != null) {
          widget.errorCallback!(data, response);
        }
      }
    });
  }

  _showError() {
    setState(() {
      layoutState = LayoutState.Error;
    });
  }

  @override
  void setState(fn) {
    //重写setState，加一个安全判断，Widget是否安装在tree上
    if(mounted) {
      super.setState(fn);
    }
  }
}
